package agents;

import java.io.FileNotFoundException;
import java.io.IOException;

import environment.Tablero;
import gui.PropertyFileReader;
import gui.TableroGUI;
import gui.Ventana;
import jade.core.Agent;
import jade.core.behaviours.TickerBehaviour;
import jade.wrapper.ControllerException;
import jade.wrapper.PlatformController;

public class Overseer extends Agent {
	private Tablero tablero;
	private TableroGUI tableroGUI;

	protected void setup()	{
		String[] prop = null;
		
		try	{
			prop = PropertyFileReader.getProperties();
		} catch (FileNotFoundException e) {
			System.out.println("Error FileNotFound");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("Error IOException");
			e.printStackTrace();
		}
		
		int tabSize;
		int tabPackages;
		String agentCls;
		int numAgents;
		int agentTck;
		if (prop != null) {
			System.out.println("Properties loaded");
			tabSize = Integer.parseInt(prop[0]);
			tabPackages = Integer.parseInt(prop[1]);
			agentCls = prop[2];
			numAgents = Integer.parseInt(prop[3]);
			agentTck = Integer.parseInt(prop[4]);
		} else {
			System.out.println("No properties loaded, using default");
			tabSize = 10;
			tabPackages = 16;
			agentCls = "agents.Reactive";
			numAgents = 1;
			agentTck = 500;		
		}
		
		this.tablero = new Tablero(tabSize, tabPackages);
		initVentana();
		while ( (this.tablero == null) && (this.tableroGUI == null) ) {}
		
		PlatformController container = getContainerController();


		Object[] argumentos = new Object[2];
		argumentos[0] = tablero;
		argumentos[1] = agentTck;
		
		for (int i=numAgents; i>0; i--) {
		
			try	{
				container.createNewAgent("ag"+i,agentCls,argumentos).start();
			} catch (ControllerException e) {
				System.out.println("Error");
				e.printStackTrace();
			}
		}
		
		addBehaviour(new TickerBehaviour(this, 1000) {
			@Override
			protected void onTick() {
				if (tablero.getActivePackages() == 0) {
					System.out.println("END");
					doDelete();
				}
			}
		});
		
		
	}
	
	/***/
	
	public void takeDown() {
		//TELL ENERGY USE
		System.out.println("Problem solved");
		System.out.println("Total Energy Use: " + tablero.getUsedEnergy() + " energy units");
	}
	
	/***/
	
	private void initVentana() {
		class CustomRunnable implements Runnable {
        Tablero t;
        CustomRunnable(Tablero tab) { t = tab; }
        
        public void run() {
        	new Ventana(t).setVisible(true);
        }
    }
		java.awt.EventQueue.invokeLater(new CustomRunnable(tablero));
	}
	
	/***/

}
